﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class Balance_PayController : UserController
    {
        public IOrdersService _orders { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        public IUser_amount_logService _user_amount_log { get; set; }
        [HttpPost]
        public IActionResult Post([FromForm]string pay_order_no, [FromForm]string pay_subject)
        {
            string order_no = pay_order_no.ToUpper();
            Orders modelorders = _orders.GetModel(order_no);
            if (modelorders == null)
            {
                return Ok(new { status = 0, msg = "订单详情获取出错" });
            }
            decimal order_amount = modelorders.order_amount;
            string subject = pay_subject;
            if (order_no == "" || order_amount == 0)
            {
                return Content("对不起，您提交的参数有误！");
            }
            //检查是否已登录
            Users userModel = GetUserInfo();
            if (userModel == null)
            {
                return Ok(new { status = 0, msg = "尚未登录" });
            }
            if (userModel.amount < order_amount)
            {
                return Ok(new { status = 0, msg = "账户的商城余额不足" });
            }

            if (order_no.StartsWith("B")) //B开头为商品订单
            {
                Orders model = _orders.GetModel(order_no);
                if (model == null)
                {
                    return Ok(new { status = 0, msg = "商品订单号不存在" });
                }
                if (model.payment_status == 1)
                {
                    //执行扣取账户金额
                    int result = _user_amount_log.Add(userModel.id, userModel.user_name, -1 * order_amount, subject);
                    if (result > 0)
                    {
                        //更改订单状态
                        bool result1 = _orders.UpdateField(order_no, "status=2,payment_status=2,payment_time='" + DateTime.Now + "'");
                        if (!result1)
                        {
                            return Ok(new { status = 0, msg = "订单更新失败！" });
                        }
                        //扣除积分
                        if (model.point < 0)
                        {
                            _user_point_log.Add(model.user_id, model.user_name, model.point, "换购扣除积分，订单号：" + model.order_no, false);
                        }
                    }
                    else
                    {
                        return Ok(new { status = 0, msg = "订单更新失败！" });
                    }
                }
                return Ok(new { status = 1, msg = "支付成功", order_no = order_no });
            }
            return Ok(new { status=0,msg= "找不到需要支付的订单类型" });
        }
    }
}